import { createSlice, type PayloadAction } from '@reduxjs/toolkit';

interface User {
  id: string;
  username: string;
  role: string;
  department?: string;
  email?: string;
  phone?: string;
}

interface UserState {
  user: User | null;
  isLoggedIn: boolean;
}

const initialState: UserState = {
  user: null,
  isLoggedIn: false,
};

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    login: (state, action: PayloadAction<User>) => {
      state.user = action.payload;
      state.isLoggedIn = true;
      // 同时存储到 localStorage
      localStorage.setItem('user', JSON.stringify(action.payload));
      localStorage.setItem('isLoggedIn', 'true');
    },
    logout: (state) => {
      state.user = null;
      state.isLoggedIn = false;
      // 清除 localStorage
      localStorage.removeItem('user');
      localStorage.removeItem('isLoggedIn');
    },
    initializeUser: (state) => {
      // 从 localStorage 初始化用户状态
      const storedUser = localStorage.getItem('user');
      const storedIsLoggedIn = localStorage.getItem('isLoggedIn');

      if (storedUser && storedIsLoggedIn === 'true') {
        state.user = JSON.parse(storedUser);
        state.isLoggedIn = true;
      }
    },
  },
});

export const { login, logout, initializeUser } = userSlice.actions;
export default userSlice.reducer;